﻿using UnityEngine;
using System.Collections;

public class CardBehaviourScript : MonoBehaviour {

	private bool rotating = false;
	private int direction = 0;
	private GameObject parentGrid;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (rotating && ((direction > 0 && transform.eulerAngles.y <= 180) ||
		        (direction < 0 && transform.eulerAngles.y > 180 && transform.eulerAngles.y <= 360))) {
			transform.Rotate(Vector3.up * Time.deltaTime * 1000, Space.World);
		} else if (rotating) {
			rotating = false;
			parentGrid.GetComponent<GridBehaviourScript> ().Rotating = rotating;
			if (direction > 0) {
				transform.eulerAngles = new Vector3(0, 180, 0);
				parentGrid.GetComponent<GridBehaviourScript> ().NbCardTurned++;
			} else {
				transform.eulerAngles = new Vector3(0, 0, 0);
				//parentGrid.GetComponent<GridBehaviourScript> ().NbCardTurned--;
			}
			direction = 0;
		}
	}

	public void turnCard(GameObject grid) {
		parentGrid = grid;
		rotating = true;
		parentGrid.GetComponent<GridBehaviourScript> ().Rotating = rotating;
		this.transform.RotateAround (this.transform.position, new Vector3 (0, 1, 0), 0.1f);
		if (transform.eulerAngles.y < 180) {
			direction = 1;
		} else {
			direction = -1;
		}
	}
	
	void OnMouseDown() {
		// Alert grid that this card was clicked
		if (transform.eulerAngles.y < 180) {
			this.transform.parent.GetComponent<GridBehaviourScript>().OnCardClick(this.transform);
		}
	}

}
